package com.leyou.item.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * *
 * Created by IntelliJ IDEA.
 * Author: caoLei
 * Date: 2018/10/22
 * Time: 17:12
 * *
 */
@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 根据查询条件分页查询品牌
     *
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @param key
     * @return
     */

    public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer rows, String sortBy, Boolean desc, String key) {

        // 开始分页
        PageHelper.startPage(page, rows);
        // 过滤
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) {
            example.createCriteria().andLike("name", "%" + key + "%")
                    .orEqualTo("letter", key);
        }

        if (StringUtils.isNotBlank(sortBy)) {
            // 排序
            example.setOrderByClause(sortBy + " " + (desc ? "desc" : "asc"));
        }
        // 查询
        List<Brand> brands = this.brandMapper.selectByExample(example);

        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        // 返回结果
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
    }


    /**
     * 新增品牌
     *
     * @param brand
     * @param cids
     */


    public void saveBrand(Brand brand, List<Long> cids) {

        //新增品牌信息
        Boolean flag = this.brandMapper.insertSelective(brand) == 1;

        if (flag) {
            //新增分类品牌和分类中间表
            for (Long cid : cids) {
                this.brandMapper.insertCategoryBrand(cid, brand.getId());
              //  cids.forEach(cid -> this.brandMapper.insertCategoryBrand(cid, brand.getId()));

            }
        }

    }

    /**
     * 根据分类查询品牌
     * 有中间表（tb_category_brand），需要自己编写sql
     * @param cid
     * @return
     */
    public List<Brand> queryBrandsByCid(Long cid) {

        return this.brandMapper.queryByCategoryId(cid);

    }

    /**
     * 根据商品品牌id，查询商品品牌
     * @param id
     * @return
     */
    public Brand queryBrandById(Long id) {
        return this.brandMapper.selectByPrimaryKey(id);
    }


    /**
     * 根据品牌id集合批量查询品牌
     * @param ids
     * @return
     */
    public List<Brand> queryBrandByIds(List<Long> ids) {
        return brandMapper.selectByIdList(ids);
    }
}
